package com.yqd.lesson.actor.serven

import scala.concurrent.duration._
import akka.actor.{Actor, ActorRef, ActorSystem, Props, Terminated}
import akka.routing.ActorRefRoutee
import akka.routing.Router
import akka.routing.RoundRobinRoutingLogic

class Routes extends Actor {
  var router = {
    val routees = Vector.fill(5) {
      val r = context.actorOf(Props[Sender])
      context watch r
      ActorRefRoutee(r)
    }
    Router(RoundRobinRoutingLogic(), routees)
  }

  def receive = {
    case w: String =>
      router.route(w, sender())
    case Terminated(a) =>
      router = router.removeRoutee(a)
      val r = context.actorOf(Props[Sender])
      context watch r
      router = router.addRoutee(r)
  }
}

object Routes extends  App{
  val system = ActorSystem("akka");
  val sender: ActorRef = system.actorOf(Props[Routes], "myactor")

  var count = 0;
  import system.dispatcher
  system.scheduler.schedule(1.second,1.second){
    count += 1;
    println("record:" + count)
    sender ! "" + count
  }
}
